/**
 * ajax文件上传
 */
(function($) {
	$.fn.getFormData = function() {
		var form_data = {};
		$(this).find("[name]").each(function(i, n) {
					var val = $(n).val();
					if ($(n).is(":file")) {
						val = n.files[0];
					}
					if (form_data[$(n).attr("name")] == null) {
						form_data[$(n).attr("name")] = val;
					} else if ($.isArray(form_data[$(n).attr("name")])) {
						form_data[$(n).attr("name")].push(val);
					} else {
						var d = new Array();
						d.push(form_data[$(n).attr("name")]);
						d.push(val);
						form_data[$(n).attr("name")] = d;
					}
				});
		return form_data;
	}
	// 上传文件
	$.ajax_upload = function(url, data, config) {
		tip_loading.show();
		var setting = {
			uploadProgress : function() {},
			uploadComplete : function() {},
			uploadFailed : function() {},
			uploadCanceled : function() {},
			isZip : true
		};
		if (typeof(config) == "function") {
			setting.uploadComplete = config;
		} else if (typeof(config) == "object") {
			setting = $.extend(setting, config);
		}
		var xhr = new XMLHttpRequest();
		var fd = new FormData();
		// 关联表单数据,可以是自定义参数
		for (var o in data) {
			if ($.isArray(data[o])) {
				for (var i = 0; i < data[o].length; i++) {
					if (data[o][i] != null) {
						fd.append(o, data[o][i]);
					}
				}
			} else {
				if (data[o] != null) {
					fd.append(o, data[o]);
				}
			}
		}
		// alert(JSON.stringify(data));
		// 监听事件
		xhr.upload.addEventListener("progress", function(evt) {
					setting.uploadProgress(evt.total, evt.loaded);
				}, false);
		xhr.addEventListener("load", function(evt) {
					tip_loading.hide();
					var json = evt.target.responseText;
					try {
						json = jQuery.parseJSON(json);
					} catch (e) {}
					setting.uploadComplete(json);
				}, false);
		xhr.addEventListener("error", setting.uploadProgress, false);
		xhr.addEventListener("abort", setting.uploadProgress, false);
		// 发送文件和表单自定义参数
		xhr.open("POST", url);
		xhr.send(fd);
		return xhr;
	}
	$.fn.ajax_upload = function(url, config) {
		var data = $(this).getFormData();
		return $.ajax_upload(url, data, config);
	}
	$.localResizeIMG = function(file, op) {
		var setting = {
			width : 640,
			quality : 0.8,
			before : function() {},
			success : function() {}
		};
		if (typeof(op) == "function") {
			setting.success = op;
		} else if (typeof(op) == "object") {
			setting = $.extend(setting, op);
		}
		var URL = window.URL || window.webkitURL;
		var blob = URL.createObjectURL(file);
		// 执行前函数
		setting.before(this, blob, file);
		_create(blob, setting);
	}
	function _create(blob, op) {
		var img = new Image();
		img.src = blob;
		img.onload = function() {
			var that = this;
			// 生成比例
			var w = that.width, h = that.height, scale = w / h;
			if (w > op.width) {
				w = op.width || w;
				h = w / scale;
			}
			// 生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			$(canvas).attr({
						width : w,
						height : h
					});
			ctx.drawImage(that, 0, 0, w, h);
			/**
			 * 生成base64 兼容修复移动设备需要引入mobileBUGFix.js
			 */
			var base64 = canvas.toDataURL('image/jpeg', op.quality || 0.8);
			// 修复IOS
			if (navigator.userAgent.match(/iphone/i)) {
				var mpImg = new MegaPixImage(img);
				mpImg.render(canvas, {
							maxWidth : w,
							maxHeight : h,
							quality : op.quality || 0.8
						});
				base64 = canvas.toDataURL('image/jpeg', op.quality || 0.8);
			}
			// 修复android
			if (navigator.userAgent.match(/Android/i)) {
				var encoder = new JPEGEncoder();
				base64 = encoder.encode(ctx.getImageData(0, 0, w, h), op.quality * 100 || 80);
			}
			// 生成结果
			var result = {
				base64 : base64,
				clearBase64 : base64.substr(base64.indexOf(',') + 1)
			};
			// 执行后函数
			op.success(result);
		};
	}
})(jQuery);